
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-03-29 18:22:35                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： UCGomePayDFService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using BestTrader.Cms.ViewModels;
using BestTrader.Cms.Models;
using AutoMapper;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;

namespace BestTrader.Cms.Services
{
    public class UCGomePayDFService : IUCGomePayDFService
    {
        private readonly IUCGomePayDFRepository _repository;
        private readonly GomePayClientService _gomePayClientService;
        private readonly IMapper _mapper;
        private readonly ILogger<UCGomePayDFService> _logger;


        public UCGomePayDFService(
            IUCGomePayDFRepository repository
           , GomePayClientService gomePayClientService
           , IMapper mapper
           , ILogger<UCGomePayDFService> logger
         )
        {
            _repository = repository;
            _gomePayClientService = gomePayClientService;
            _mapper = mapper;
            _logger = logger;
        }


        public TableDataResult<string> AddGomePayDaiFu(GomePayDFAddModel input, string userId)
        {
            var now = DateTime.Now;

            var result = new TableDataResult<string>() { Success = false };

            decimal Amount = decimal.Parse(input.Amount);
            var uMoney = Math.Abs(Math.Round(Amount, 2));

            var ucGomePayModel = _mapper.Map<UCGomePayDF>(input);
            ucGomePayModel.Amount = uMoney.ToString();
            ucGomePayModel.Currency = "CNY";
            ucGomePayModel.AddTime = now;
            ucGomePayModel.AddManagerId = userId.ToInt32();
            // _ucGomePayDFService.GetGomePayDFBillByOrderNumbe();
            ///
           //var  orderResult =   _gomePayClientService.GetGomePayDFBillByOrderNumber(ucGomePayModel.OrderNumber).Result;
            var insertResult = _repository.Insert(ucGomePayModel);
            if (insertResult > 0)
            {
                var model = _mapper.Map<GomePayDFModel>(input);
                model.Amount = uMoney.ToString();
                var json = _gomePayClientService.AddGomePayDF(model).Result;
                var resultData = JsonConvert.DeserializeObject<GomePayDFOutput>(json);
                if (resultData != null)
                {
                    var dfEntity = _repository.Get(insertResult.Value);
                    if (resultData.op_ret_code == "000")
                    {
                        dfEntity.State = 1;
                        dfEntity.GPCode = resultData.op_ret_code;
                        dfEntity.GPOrderId = resultData.orderid;
                        result.Success = true;
                        _logger.LogWarning($"美付宝支付成功OrderNo:{resultData.order_number},orderid:{resultData.orderid},op_ret_code:{resultData.op_ret_code},op_err_msg:{resultData.op_err_msg},op_err_obj:{resultData.op_err_obj}");
                    }
                    else
                    {
                        dfEntity.State = 2;
                        dfEntity.GPCode = resultData.op_ret_code;
                        dfEntity.GPOrderId = resultData.orderid;
                        result.ResultCode = ResultCodeAddMsgKeys.GomePayCommonErrorCode;
                        result.ResultMsg = "GomePay:" + resultData.op_err_msg;
                        _logger.LogError($"美付宝支付失败OrderNo:{resultData.order_number},orderid:{resultData.orderid},op_ret_code:{resultData.op_ret_code},op_err_msg:{resultData.op_err_msg},op_err_obj:{resultData.op_err_obj}");

                    }
                    _repository.Update(dfEntity);
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.GomePayCommonErrorCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.GomePayCommonErrorMsg;
                }
            }
            return result;
        }
        /// <summary>
        /// 查询支付结果
        /// </summary>
        /// <param name="OrderNo"></param>
        /// <returns></returns>
        public TableDataResult<GomePayDFBillOutput> GetGomePayDFBillByOrderNo(string OrderNo)
        {
            //OrderNo = "QS10043320190412173050";
            var result = new TableDataResult<GomePayDFBillOutput>() { Success = false };
            var json = _gomePayClientService.GetGomePayDFBillByOrderNumber(OrderNo).Result;
            var resultData = JsonConvert.DeserializeObject<GomePayDFBillQueryResultOutput>(json);
            if (resultData != null)
            {
                if (resultData.op_ret_code == "000")
                {
                    result.Data = _mapper.Map<GomePayDFBillOutput>(resultData);
                    result.Success = true;
                }
                else {
                    result.ResultCode = ResultCodeAddMsgKeys.GomePayCommonErrorCode;
                    result.ResultMsg = "GomePay:" + resultData.op_err_msg;
                }
            }

            return result;

        }

        //GomePayDFBillOutput
        /// <summary>
        /// 美付宝代付记录
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public TableDataModel LoadOutCashRecordData(InOutCoinRecordRequestModel model, String userId, String roleId)
        {

            string conditions = $"where 1=1";
            return LoadData(model, conditions);
        }

        public TableDataModel LoadData(InOutCoinRecordRequestModel model, String conditions)
        {
            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $"and (OrderNumber like '%{model.Key}%' or CustomerName like '%{model.Key}%' or UserName like '%{model.Key}%') ";
            }
            if (model.State.HasValue)
            {
                conditions += $"and State = {model.State} ";
            }
            if (model.Start.HasValue)
            {
                conditions += $"and AddTime >='{ model.Start.Value }' ";
            }
            if (model.End.HasValue)
            {
                conditions += $"and AddTime <='{ model.End.Value.Date.AddDays(1).AddSeconds(-1) }' ";
            }
            if (!model.ManagerId.IsNullOrWhiteSpace())
            {
                conditions += $"and ManagerId = {model.ManagerId} ";
            }
            var list = _repository.GetListPaged(model.Page, model.Limit, conditions, "Id desc").ToList();
            var result = new List<UCGomePayDF>();
            foreach (var item in list)
            {
                item.Amount = item.Amount;
                item.Amount = item.Amount;// Math.Abs(item.RMBMoney ?? 0);
                result.Add(item);
            }
            return new TableDataModel
            {
                count = _repository.RecordCount(conditions),
                data = result
            };
        }



    }
}